package com.hnchances.wjb.controller;

import com.hnchances.wjb.Service.Impl.MsmServiceImpl;
import com.hnchances.wjb.common.R;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.security.Security;

@ApiOperation("自己测试写的controller")
@Controller
public class myController {
    @RequestMapping({"/","/index"})
    public String ToIndex(Model model){
model.addAttribute("msg","hello,shiro");
return "index";
    }

    @RequestMapping("/user/add")
    public String ToAdd(Model model){
        model.addAttribute("msg","hello,shiro");
        return "/user/add";
    }

    @RequestMapping("/user/update")
    public String ToUpdate(Model model){
        model.addAttribute("msg","hello,shiro");
        return "/user/update";
    }

    @RequestMapping("/toLogin")
    public String ToLogin(Model model){
        model.addAttribute("msg","hello,shiro");
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        System.out.println(subject);
        //封装用户的登陆数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        try {
            subject.login(token);
            return "index";
        }catch (UnknownAccountException e){//用户名错误
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){//密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }

    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String noAuthorized(){
return "未经授权无法访问该页面";
    }

    @Autowired
    MsmServiceImpl msmService;
    @ResponseBody
    @RequestMapping("/code")
    public R ToLogin(@RequestBody String phone) throws IOException {
        msmService.code(phone);
        return R.success(msmService.code(phone));
    }

}
